package com.lccviolet;

import java.util.HashMap;
import java.util.WeakHashMap;

/**
 * @author LiChaochao
 * @Date 2021/9/22 21:18
 * @Description WeakHashMap：key弱引用，gc之后，该k-v键值对会被回收
 */
public class WeakHashMapDemo {

    public static void main(String[] args) {
        myHashMap();
        System.out.println("===============================");
        myWeakHashMap();
    }

    // 强引用HashMap
    private static void myHashMap() {
        HashMap<Integer, String> map = new HashMap<>();
        Integer key = new Integer(1);
        String value = "HashMap";

        map.put(key, value);
        System.out.println(map);

        // map中存进去的key，与new Integer(1)有关系，而与key引用无关
        // 因此，输出结果仍为{1=HashMap}
        key = null;
        System.out.println(map);

        System.gc();
        System.out.println(map);
    }

    // 弱引用WeakHashMap
    private static void myWeakHashMap() {
        WeakHashMap<Integer, String> map = new WeakHashMap<>();
        Integer key = new Integer(2);
        String value = "WeakHashMap";

        map.put(key, value);
        System.out.println(map);

        key = null;
        System.out.println(map);

        System.gc();
        System.out.println(map);
    }
}
